package com.zxbit.uangstore.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.zxbit.uangstore.BuildConfig;
import com.zxbit.uangstore.R;
import com.zxbit.uangstore.main.MainActivity;

import java.io.File;

public class ApkUtils {

    public static String INSTALL_TYPE = "application/vnd.android.package-archive";

    public static void install(Context context, String filePath) {
        String TAG = "ApkUtils";
        DebugLog.i(TAG, "开始执行安装: " + filePath);
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            DebugLog.w(TAG, "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context,
                    BuildConfig.APPLICATION_ID + ".fileprovider", apkFile);
            intent.setDataAndType(contentUri, INSTALL_TYPE);
        } else {
            DebugLog.w(TAG, "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), INSTALL_TYPE);
        }
        context.startActivity(intent);
    }

    public static void open(Context activity, String packageName) {
        Intent intent = activity.getPackageManager().getLaunchIntentForPackage(packageName);
        if (intent != null) {
            activity.startActivity(intent);
        } else {
            ToastUtils.showShort((Activity) activity, activity.getResources().getString(R.string.main_product_open_err));
        }
    }

    /**
     * @param activity
     * @param appPkg   应用的包名
     */
    public static void launchAppDetail(Activity activity, String appPkg) {
        final String GOOGLE_PLAY = "com.android.vending";//谷歌商店
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GOOGLE_PLAY);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
        } catch (Exception e) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri content_url = Uri.parse("https://play.google.com/store/apps/details?id=" + appPkg);
            intent.setData(content_url);
            activity.startActivity(intent);
        }
    }

    public static void installOrOpen(Context activity, boolean isInstall, String packageName) {
        if (isInstall) {
            //已安装，打开程序
            open(activity, packageName);
        } else {
            //未安装，跳转至谷歌Play下载该程序
            launchAppDetail((Activity) activity, packageName);
        }
    }
}
